<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/8
 * Time: 16:03
 */
namespace app\manage\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder; // 引入ZBuilder
use app\common\controller\Core;
use app\common\model\Users as UsersM; //会员表
use app\common\model\Rank as RankM; //级别表
use app\common\model\Msg as MsgM; //会员消息表
use app\common\model\Banklist as BanklistM; //银行表
use app\common\model\Level as LevelM;
use app\common\model\Meal as MealM;
use app\common\model\Team as TeamM;
use think\App;
use think\Db;

class Users extends Admin
{
    public $rule = [];
    public function __construct(App $app = null){
        $this->rule=Db::name('qt_user_role')->column('name','id');
        parent::__construct($app);
    }

    // 业务员列表
    public function lists()
    {
        $map = $this->getMap();
        $order = $this->getOrder();
        $data_list=UsersM::order('id desc')->where($map)->order($order)->paginate();
        $page=$data_list->render();
        //设置按钮
        $btn_edit = [
            'title' => '编辑员工',
            'icon'  => 'fa fa-fw fa-edit',
            'class' => 'btn btn-xs btn-default',
            'href'  => url('edit', ['id' => '__id__']),
        ];
        // 数据列表
        $btn_access = [
            'title' => '新增员工',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-info',
            'href' => url('add'),
        ];
        //设置页面
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addColumn('id', 'ID', 'text')
            ->addColumn('real_name','员工姓名','text')
            ->addColumn('sex','性别','status','',['1'=>'男:success','2'=>'女:danger'])
            ->addColumn('phone', '手机', 'text')
            ->addColumn('work_number', '工号', 'text')
            ->addColumn('work_time', '入职日期', 'datetime','','Y-m-d')
            ->addColumn('avatar', '头像', 'picture')
            ->addColumn('role','会员角色','status','',$this->rule)
            ->addColumn('status','状态','status','',['1'=>'冻结:danger','0'=>'正常:success','3'=>'审核中:info','4'=>'超级管理:success'])
            ->addColumn('create_time', '注册日期', 'datetime','','Y-m-d H:i')
            ->addColumn('right_button','操作','btn')
            ->setTableName('qt_users') // 指定数据表名
            ->setSearchArea([
                ['text:2', 'id', '会员ID', 'eq'],
                ['text:2','nickname','昵称','like'],
                ['text:2','phone','手机','eq'],
                ['select:2','status','登录状态','','',['1'=>'冻结','0'=>'正常','3'=>'审核中']],
            ])
            ->addRightButton('edit',$btn_edit,['area'=>['70%','90%']]) // 添加右侧按钮
            ->addTopButton('add', $btn_access)// 添加顶部按钮
            ->setPrimaryKey('id') // 设置主键名
            ->setPageTitle('会员列表')
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }
    //编辑业务员信息
    public function edit($id=null)
    {
        $user = UsersM::get($id);
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            if(!empty($data['new_passwd'])){
                $data['password']=pwd($data['new_passwd'],$user['ivt_code']);
                unset($data['new_passwd']);
            }
            if(!empty($data['new_safeword'])){
                $data['safeword']=pwd($data['new_safeword'],$user['ivt_code']);
                unset($data['new_safeword']);
            }
            $data['work_time'] = strtotime($data['work_time']);
            if (UsersM::update($data)) {
                $this->success('修改信息成功','',['_close_pop' => 1,'_parent_reload' => 1]);
            }else{
                $this->error('编辑失败');
            }
        }else
        {
            $postRes = Db::name('qt_post')->where('status','1')->column('title','id');
            $groupRes = Db::name('qt_group')->whereNotIn('pid','0,1')->where('status','1')->column('name','id');
            $teamRes = Db::name('qt_group')->whereIn('pid','0,1')->where('status','1')->column('name','id');
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['hidden','id','id'],
                        ['text','nickname','员工姓名'],
                        ['text','work_number','工号'],
                        ['datetime','work_time','入职日期'],
                        ['text','phone','手机号码'],
                        ['image','avatar','头像'],
                        ['password','new_passwd','登录密码'],
                        ['Linkage','team_id','所属公司','<code>请选择所属公司</code>',$teamRes,'',url('get_group'),'group_id,post_id'],
                        ['Linkage','group_id','所属部门','<code>请选择所属部门</code>',$groupRes,'',url('get_post'),'post_id'],
                        ['select', 'post_id', '所属岗位', '', $postRes],
                        ['radio','status','会员状态','冻结后禁止登录',['1'=>'冻结','0'=>'正常','3'=>'审核中']],
                    ]
                )
                ->setFormData($user)
                ->setPageTitle('员工信息')
                ->fetch();
        }
    }


    //添加员工信息
    public function add( )
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $data['create_time'] = time();
            $insert = Db::name('qt_users')->insertGetId($data);
            $updateData['ivt_code'] = $insert;
            $updateData['password']=pwd($data['new_passwd'],$insert);
            $update = Db::name('qt_users')->where('id',$insert)->update($updateData);
            if ($update) {
                $this->success('添加员工成功','lists');
            }else{
                $this->error('添加失败');
            }
        }else
        {
            $postRes = Db::name('qt_post')->where('status','1')->column('title','id');
            $groupRes = Db::name('qt_group')->whereNotIn('pid','0,1')->where('status','1')->column('name','id');
            $teamRes = Db::name('qt_group')->whereIn('pid','0,1')->where('status','1')->column('name','id');
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['hidden','id','id'],
                        ['text','nickname','员工姓名'],
                        ['text','work_number','工号'],
                        ['datetime','work_time','入职日期'],
                        ['text','phone','手机号码'],
                        ['image','avatar','头像'],
                        ['password','new_passwd','登录密码'],
                        ['Linkage','team_id','所属公司','<code>请选择所属公司</code>',$teamRes,'',url('get_group'),'group_id,post_id'],
                        ['Linkage','group_id','所属部门','<code>请选择所属部门</code>',$groupRes,'',url('get_post'),'post_id'],
                        ['select', 'post_id', '所属岗位', '', $postRes],
                        ['radio','status','会员状态','冻结后禁止登录',['1'=>'冻结','0'=>'正常','3'=>'审核中'],'0'],
                    ]
                )
                ->setPageTitle('新增员工')
                ->fetch();
        }
    }



    //资金变动
    public function recharge($id=null){
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            if($data['content'])
            {
                $core=NEW Core();
                if($data['num']<>0){
                    //积分
                    if($data['flag'] == '2'){
                        $type = '4';
                    }
                    //余额
                    if($data['flag'] == '1'){
                        $type = '5';
                    }
                    $core->add_log($id,$data['num'],$data['check'],$type,$data['flag'],$data['content']);
                }
                $this->success('账户余额变动成功','',['_close_pop' => 1,'_parent_reload' => 1]);
            }else
            {
                $this->error('请填写变动备注信息！');
            }
        }else{
            $user=UsersM::where('id',$id)->find();
            $res['user_info']='账号：'.$user['phone'];
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['radio:7','flag','变动账户','',['1'=>'账户余额','2'=>'积分']],
                        ['radio:7','check','变动类型','',['1'=>'增加','2'=>'减少']],
                        ['static:7','user_info','账户信息'],
                        ['number:7','num','账户余额', '<span class="text-danger">余额：'.$user['money'].'积分：'.$user['point'].'</span>'],
                        ['text:7','content','变动备注'],
                    ]
                )
                ->setPageTips('谨慎操作')
                ->setFormData($res)
                ->setPageTitle('资金变动')
                ->submitConfirm()
                ->fetch();
        }
    }

    /**
     * 获取当前团队下面的岗位
     * @param $team_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_post($group_id){
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $data= Db::name('qt_group_post')
            ->alias('gp')
            ->leftJoin('qt_post p','gp.post_id = p.id')
            ->where('group_id',$group_id)
            ->field('p.id,p.title')
            ->select(); //数据
        $result = [];
        foreach ($data as $key=>$value){
            $result[$key]['key'] = $value['id'];
            $result[$key]['value'] = $value['title'];
        }
        $arr['list'] = $result;
        return json($arr);
    }


    private function getGroup($team_id){
        static $res = array();
        $groupRes = Db::name('qt_group')->where('team_id',$team_id)->select();
        if(empty($groupRes)){
            return $res;
        }else{
            foreach ($groupRes as $key=>$value){
                $res[] = $value;
                $chileGroupRes = Db::name('qt_group')->where('pid',$value['id'])->select();
                if(!empty($chileGroupRes)){
                    $this->getGroup($value['id']);
                }
            }
            return $res;
        }
    }


    /**
     * 获取当前团队下面的岗位
     * @param $team_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_group($team_id){
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $data = $this->getGroup($team_id);
        $result = [];
        foreach ($data as $key=>$value){
            $result[$key]['key'] = $value['id'];
            $result[$key]['value'] = $value['name'];
        }
        $arr['list'] = $result;
        return json($arr);
    }


}